﻿using System;
using System.Xml;

namespace Pibby.Core.Feeds
{
	public enum EnclosureMimeType
	{
		Unknown,
		Audio
	}

	/// <summary>
	/// A reference to a resource in an rss feed.
	/// </summary>
	public class Enclosure
	{
		#region Xml Constants

		const string EnclosureNode = "enclosure";
		const string UrlAttribute = "url";
		const string LengthAttribute = "length";
		const string TypeAttribute = "type";

		const string AudioMimeType = "audio/";

		#endregion

		#region Constructors

		protected Enclosure()
		{
		}

		/// <summary>
		/// Create a new enclosure object from an xml fragment
		/// </summary>
		/// <param name="element"></param>
		/// <returns></returns>
		public static Enclosure Create(XmlReader reader)
		{
			if (reader == null)
			{
				throw new ArgumentNullException("reader", Resources.Enclosure_NullObjectError);
			}

			var enclosure = new Enclosure();

			if (reader.Name.Equals(EnclosureNode, StringComparison.CurrentCultureIgnoreCase))
			{
				string url = reader.GetAttribute(UrlAttribute);

				if (!string.IsNullOrEmpty(url))
					enclosure.Url = new Uri(url);

				string length = reader.GetAttribute(LengthAttribute);

				if (!string.IsNullOrEmpty(length))
					enclosure.Length = Convert.ToInt32(length, System.Globalization.CultureInfo.InvariantCulture);

				string type = reader.GetAttribute(TypeAttribute);

				if (!string.IsNullOrEmpty(type))
				{
					if (type.StartsWith(AudioMimeType, StringComparison.OrdinalIgnoreCase))
						enclosure.MimeType = EnclosureMimeType.Audio;
				}
				else if (enclosure.Url != null && enclosure.Url.AbsoluteUri.EndsWith(FileConstants.Mp3FileExtension, StringComparison.OrdinalIgnoreCase))
				{
					enclosure.MimeType = EnclosureMimeType.Audio;
				}
			}

			return enclosure;
		}

		public static Enclosure Create(string fileName)
		{
			if (string.IsNullOrEmpty(fileName))
				throw new ArgumentNullException("fileName", Resources.Enclosure_BlankStringError);

			var enclosure = new Enclosure();

			if (fileName.EndsWith(FileConstants.Mp3FileExtension, StringComparison.OrdinalIgnoreCase))
			{
				enclosure.Url = new Uri(fileName);
				enclosure.Length = 0;
				enclosure.MimeType = EnclosureMimeType.Audio;
			}

			return enclosure;
		}

		#endregion

		public override string ToString()
		{
			return string.Format(System.Globalization.CultureInfo.CurrentUICulture, "{0} {1} bytes", this.Url, this.Length);
		}

		#region Properties

		public Uri Url
		{
			get;
			private set;
		}

		public long Length
		{
			get;
			private set;
		}

		public EnclosureMimeType MimeType
		{
			get;
			private set;
		}

		#endregion

	}
}
